<template>
    <div  v-loading="pasteUploading" element-loading-text="粘贴图片上传中">
        <textarea  :id="tinymceId" class="tinymce-textarea"></textarea >
        <FileUploadDialog ref="fileupload" :on-success-callback="uploadSuccess" :data="{path: path}" accept="image/gif, image/jpeg, image/png" :limit="1" title="图片上传"></FileUploadDialog>

    </div>
</template>

<script>
    import tinymce from 'tinymce/tinymce.min.js'
    import './zh_CN.js'
    import 'tinymce/themes/silver/theme'
    import 'tinymce/plugins/advlist'
    import 'tinymce/plugins/anchor'
    import 'tinymce/plugins/autolink'
    import 'tinymce/plugins/autosave'
    import 'tinymce/plugins/code'
    import 'tinymce/plugins/codesample'
    import 'tinymce/plugins/colorpicker'
    import 'tinymce/plugins/contextmenu'
    import 'tinymce/plugins/directionality'
    import 'tinymce/plugins/emoticons'
    import 'tinymce/plugins/fullscreen'
    import 'tinymce/plugins/hr'
    import 'tinymce/plugins/image'
    import 'tinymce/plugins/imagetools'
    import 'tinymce/plugins/importcss'
    import 'tinymce/plugins/insertdatetime'
    import 'tinymce/plugins/link'
    import 'tinymce/plugins/lists'
    import 'tinymce/plugins/media'
    import 'tinymce/plugins/nonbreaking'
    import 'tinymce/plugins/noneditable'
    import 'tinymce/plugins/pagebreak'
    import 'tinymce/plugins/paste'
    import 'tinymce/plugins/preview'
    import 'tinymce/plugins/print'
    import 'tinymce/plugins/save'
    import 'tinymce/plugins/searchreplace'
    import 'tinymce/plugins/spellchecker'
    import 'tinymce/plugins/tabfocus'
    import 'tinymce/plugins/table'
    import 'tinymce/plugins/template'
    import 'tinymce/plugins/textcolor'
    import 'tinymce/plugins/textpattern'
    import 'tinymce/plugins/visualblocks'
    import 'tinymce/plugins/visualchars'
    import 'tinymce/plugins/wordcount'
    import 'tinymce/skins/ui/oxide/skin.min.css'

    import 'tinymce/icons/default/index.js'
    import FileUploadDialog from '../../upload/FileUploadDialog.vue'
    const plugins = ['advlist anchor autolink autosave code codesample colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount']
    const toolbar = ['bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample', 'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen mybutton']
    import {imageToDataUrl,dataUrltoFile} from '../../../tools/FileTools.js'
    import fileUploadMixin from "../../../mixin/FileUploadMixin.js"
    export default {
        name: 'TinymceEditor',
        mixins:[fileUploadMixin],
        components: {FileUploadDialog},
        props: {
            id: {
                type: String,
                default: function () {
                    return 'vue-tinymce-' + new Date().getTime() + '-' + ((Math.random() * 1000).toFixed(0) + '')
                }
            },
            value: {
                type: String,
                default: ''
            },
            path: {
                type: String,
                default: 'upload'
            },
            height: {
                type: Number,
                default: 400
            },
            pasteAutoUpload: {
                type: Boolean,
                default: true
            },
            uploadUrl:{
                type: [String ,Function]
            },
            // 是否手机预览
            mobilePreview: {
                type: Boolean,
                default: false
            },
            // 预览宽度
            previewWidth: {
                type: Number,
            },
        },
        data () {
            return {
                hasInit: false,
                flag: true,
                model: this.value,
                tinymceId: this.id,
                pasteUploading: false
            }
        },
        mounted () {
            this.init()
        },
        activated () {
            this.init()
        },
        deactivated () {
            this.destroyTinymce()
        },
        destroyed () {
            this.destroyTinymce()
        },
        methods: {
            init () {
                let _self = this
                let uploadUrl = this.uploadUrl
                if (uploadUrl && typeof uploadUrl == "function") {
                    uploadUrl = uploadUrl()
                }
                tinymce.init({
                    selector: '#' + _self.tinymceId,
                    height: _self.height,
                    toolbar: toolbar,
                    // 图片最大 宽度设置，注意这里不会和内容一起保存
                    content_style: 'img {max-width:100% !important }', // 初始化赋值
                    language: 'zh_CN',
                    plugin_preview_width: _self.previewWidth >0 ? _self.previewWidth: (_self.mobilePreview ? 375: null),
                    image_advtab: true,
                    // 允许图片粘贴
                    paste_data_images: true,
                    paste_preprocess: function (plugin, args) {
                        // 图片粘贴处理自动上传
                        if (_self.pasteAutoUpload && args.content && args.content.indexOf('<img src="blob:http') === 0) {
                            let el = document.createElement( 'div' )
                            el.innerHTML =  args.content
                            // 是粘贴的图片
                            let imageUrl = el.getElementsByTagName( 'img' )[0].getAttribute('src')
                            args.content = ''
                            _self.pasteUploading = true
                            imageToDataUrl(imageUrl).then(function (dataUrl) {
                                let file = dataUrltoFile(dataUrl)
                                _self.$_fileUpload(file, {path: _self.path},uploadUrl).then(function (res) {
                                    let resContent = res.data.url
                                    _self.insertContent('<img src="' + resContent + '"/>')
                                    _self.pasteUploading = false
                                }).catch(function (error) {
                                    _self.pasteUploading = false
                                    if(error.response){
                                        _self.$message.error(error.response.data.msg)
                                    }else {
                                        _self.$message.error('网络错误或服务不可用')
                                    }
                                })
                            })
                        }
                    },
                    init_instance_callback: editor => {
                        if (_self.model) {
                            editor.setContent(_self.model)
                        }
                        _self.hasInit = true
                        editor.on('NodeChange Change KeyUp SetContent input undo redo', () => {
                            _self.flag = false
                            _self.$emit('input', editor.getContent())
                        })
                    },
                    plugins: plugins,
                    setup: function (editor) {
                        editor.ui.registry.addButton('myButton', {
                            text: '图片上传',
                            onAction: function () {
                                _self.$refs.fileupload.show()
                            }
                        })
                    }
                });
            },
            destroyTinymce () {
                if (tinymce.get(this.tinymceId)) {
                    tinymce.get(this.tinymceId).destroy()
                }
            },
            setContent (value) {
                if (value) {
                    tinymce.get(this.tinymceId).setContent(value)
                }
            },
            clearContent() {
                tinymce.get(this.tinymceId).setContent('')
            },
            getContent () {
                tinymce.get(this.tinymceId).getContent()
            },
            insertContent (val) {
                tinymce.get(this.tinymceId).insertContent(val)
            },
            uploadSuccess (res, file, fileList) {
                let content = res.url
                let self = this
                self.insertContent(`<img src="${content}" >`)
            }
        },
        watch: {
            value (val) {
                this.model = val
            },
            model (val) {
                if (this.hasInit && this.flag) {
                    this.setContent(val)
                }
                this.flag = true
            }
        }
    }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
